#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

static const uint16_t default_port = 8888;
static std::string default_ip = "127.0.0.1";

int main(int argc, char *argv[])
{
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);
    uint16_t port = default_port;
    //uint16_t port = std::stoi(argv[2]);
    std::string ip = default_ip;
    //std::string ip = argv[1];

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    if (sockfd < 0)
    {
        std::cout << "Socket failed" << std::endl;
        exit(1);
    }

    // 不用bind套接字，因为在发送数据时OS会自动bind，自动分配port。
    // 这个sockaddr_in 是为了标识我们要把数据发送给谁。
    memset(&client_addr, 0, sizeof(client_addr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(port);
    client_addr.sin_addr.s_addr = inet_addr(ip.c_str());

    // int flag = bind(sockfd, (const sockaddr *)&client_addr, sizeof(client_addr));
    // if (flag < 0)
    // {
    //     std::cout << "bind failed" << std::endl;
    //     exit(1);
    // }

    // 发送数据模块
    std::string message;
    while (true)
    {
        std::cout << "Please enter:";
        getline(std::cin, message);
        ssize_t n = sendto(sockfd, message.c_str(), message.size(), 0, (const sockaddr *)&client_addr, client_len);
        if(n > 0)
        {
            struct sockaddr_in temp;
            socklen_t len = sizeof(temp);
            char buffer[1024];
            ssize_t m = recvfrom(sockfd, buffer, sizeof(buffer), 0, (sockaddr *)&temp, &len);

            if(m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else
            {
                std::cout << "recvfrom failed" << std::endl;
            }
        }
        else
        {
            std::cout << "send message failed" << std::endl;
            continue;
        }

    }
    return 0;
}